from datetime import timedelta, datetime

from django.db import transaction
from django.db.models import F, Q, Count
from django.shortcuts import render
from django.utils import timezone

from saas_main import models
from saas_main.forms.projec_forms import ProjectForms, WikiForm, IssueForm, InviteForm
from saas_main.tasks import *


def project_list(request):
    form = ProjectForms()
    return render(request, 'project.html', {'form': form})


def project_dashboard(request, project):
    # 获取当前项目的用户权限
    user_right = models.UserRight.objects.filter(user=request.tracer.project.creator). \
        filter(Q(end_time__gt=datetime.now()) | Q(end_time=None)).order_by("-right__category").first()
    # 获取具体的权限内容
    right_content = user_right.right

    map_dict = {k: v for k, v in models.Issues.status_choices}
    count = models.Issues.objects.filter(project=request.tracer.project).values('status').annotate(count=Count("id"))
    for i in count:
        i.update({"name": map_dict.get(i['status'])})
    today = timezone.now().date()
    reply_qs = models.IssuesReply.objects.filter(reply_type=1, issues__project=request.tracer.project,
                                                 create_datetime__date=today).order_by("-create_datetime")

    return render(request, 'dashboard.html',
                  {
                      'pro_id': project,
                      "right_content": right_content,
                      "count": count,
                      "reply": reply_qs
                  })


class SelectFilter:
    def __init__(self, data_list, request, keyword):
        self.data_list = data_list
        self.request = request
        self.keyword = keyword

    def __iter__(self):
        params = self.request.GET.getlist(self.keyword)
        for item in self.data_list:
            data = {'value': item[0], 'name': item[1]}
            if item[0] in params:
                data['mark'] = 'selected'
            else:
                for sub_param in params:
                    if str(item[0]) in sub_param.split(","):
                        data['mark'] = 'selected'
            yield data


class CheckFilter:
    def __init__(self, data_list, request, keyword):
        self.data_list = data_list
        self.request = request
        self.keyword = keyword

    def __iter__(self):
        params = self.request.GET.getlist(self.keyword)
        for item in self.data_list:
            data = {'value': item[0], 'name': item[1]}
            if item[0] in params:
                data['mark'] = 'checked'
            else:
                for sub_param in params:
                    if str(item[0]) in sub_param.split(","):
                        data['mark'] = 'checked'
            yield data


def project_issues(request, project):
    form = IssueForm(request, project)
    pagenum = request.GET.get('pagenum')
    choices = [
        {"name": "priority__in", 'data_iter': CheckFilter(models.Issues.priority_choices, request, 'priority__in'),
         'title': '优先级'},
        {"name": "status__in", 'data_iter': CheckFilter(models.Issues.status_choices, request, 'status__in'),
         'title': "状态", },
        {"name": "issues_type__in",
         'data_iter': CheckFilter(models.IssuesType.objects.filter(project=project).values_list("id", "title"),
                                  request, 'issues_type__in'), 'title': '问题类型'},
    ]
    selects = [
        {"name": "assign__in", 'data_iter': SelectFilter(
            models.ProjectRelation.objects.filter(project=project).values_list("user__id", 'user__realname'), request,
            'assign__in'), 'title': '指派人'},
        {"name": "attention", 'data_iter': SelectFilter(
            models.ProjectRelation.objects.filter(project=project).values_list("user__id", 'user__realname'), request,
            'attention'), 'title': '关注人'},
    ]
    invite_form = InviteForm()
    return render(request, 'issues.html',
                  {
                      'pro_id': project,
                      'form': form,
                      "invite_form": invite_form,
                      "pagenum": pagenum,
                      'choices': choices,
                      'selects': selects
                  })


def project_issues_detail(request, project, issue_id):
    obj = models.Issues.objects.get(id=issue_id)
    form = IssueForm(request, project, instance=obj)
    return render(request, 'issues_detail.html', {'pro_id': project, 'issue_id': issue_id, 'form': form, "obj": obj})


def project_statistics(request, project):
    return render(request, 'statistics.html', {'pro_id': project})


def project_wiki(request, project, wiki_id=None):
    return render(request, 'wiki.html', {'pro_id': project, "wiki_id": wiki_id})


def project_wiki_add(request, project, wiki_id=None):
    if wiki_id:
        wiki_obj = models.Wiki.objects.filter(id=wiki_id).first()
        form = WikiForm(request, instance=wiki_obj, wiki_id=wiki_id)
    else:
        form = WikiForm(request, wiki_id=wiki_id)
    return render(request, 'wiki_add.html', {'pro_id': project, 'form': form, "wiki_id": wiki_id})


def project_file(request, project):
    folder_id = request.GET.get('folder_id')
    path_list = []
    if folder_id:
        obj = models.FileRepository.objects.filter(id=folder_id).first()
        while True:
            if obj:
                path_list.insert(0, obj)
                obj = obj.parent
            else:
                break

    return render(request, 'file.html', {'pro_id': project, 'folder_id': folder_id, 'path_list': path_list})


def project_setting(request, project):
    return render(request, 'setting.html', {'pro_id': project})


def project_setting_delete(request, project):
    return render(request, 'setting_delete.html', {'pro_id': project})


def project_invite_page(request):
    data = request.GET
    code_obj = models.ProjectInvite.objects.filter(project=data.get('project'), code=data.get('code')).first()
    project_obj = models.Project.objects.get(id=data.get('project'))

    # 邀请码的验证
    if not code_obj:
        return render(request, 'invite_result.html', {'pro_id': project_obj.id, 'error': '邀请码错误！'})
    if (code_obj.create_datetime + timedelta(minutes=code_obj.period)) < datetime.now():
        return render(request, 'invite_result.html', {'pro_id': project_obj.id, 'error': '邀请码已经过期了，请重新生成！'})
    if code_obj.count:
        if code_obj.use_count >= code_obj.count:
            return render(request, 'invite_result.html', {'pro_id': project_obj.id, 'error': '邀请码人数已经达到上限了！'})

    # 用户验证
    if models.ProjectRelation.objects.filter(user=request.user, project=project_obj).exists():
        return render(request, 'invite_result.html', {'pro_id': project_obj.id, 'error': '已加入项目，无需再次加入！'})

    # 项目验证
    # 获取当前项目的用户权限
    user_right = models.UserRight.objects.filter(user=project_obj.creator). \
        filter(Q(end_time__gt=datetime.now()) | Q(end_time=None)).order_by("-right__category").first()
    # 获取具体的权限内容
    right_content = user_right.right
    if project_obj.workers_num >= right_content.project_member:
        return render(request, 'invite_result.html', {'pro_id': project_obj.id, 'error': '当前项目人数已经达到上限，请联系拥有者升级套餐！'})

    try:
        with transaction.atomic():
            relation_dict = {
                'project': project_obj,
                'user': request.user,
            }
            models.ProjectRelation.objects.create(**relation_dict)
            models.Project.objects.update(workers_num=F('workers_num') + 1)
            models.ProjectInvite.objects.update(use_count=F('use_count') + 1)
            return render(request, 'invite_result.html', {'pro_id': project_obj.id})
    except Exception as e:
        raise


# http://127.0.0.1:8000/invite/?code=adc92601d2251ba747756895e9fca111&project=5

def project_cases(request, project):
    if cache.has_key("jenkins_data"):
        job_list = cache.get("jenkins_data")
    else:
        jenkins = JenkinsSdk()
        job_list = jenkins.get_job_list()['data']
        get_jenkins_list.delay()
    return render(request, 'case.html', {'job_list': job_list, "pro_id": project})
